<template>

   <a-spin :spinning="confirmLoading">
     <j-form-container :disabled="formDisabled">
       <!-- 主表单区域 -->
       <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
         <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入编号" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
     </j-form-container>
      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs" v-show='model.id'>
        <a-tab-pane tab="原料价格执行表明细" :key="refKeys[0]" :forceRender="true">

<!--          <j-editable-table-->
<!--            :ref="refKeys[0]"-->
<!--            :loading="bussMaterialPriceDetailTable.loading"-->
<!--            :columns="bussMaterialPriceDetailTable.columns"-->
<!--            :dataSource="bussMaterialPriceDetailTable.dataSource"-->
<!--            :maxHeight="300"-->
<!--            :disabled="formDisabled"-->
<!--            :rowNumber="true"-->
<!--            :rowSelection="true"-->
<!--            :actionButton="true"/>-->

<!--          <vxe-table-->
<!--            border-->
<!--            resizable-->
<!--            keep-source-->
<!--            show-overflow-->
<!--            ref="xTable"-->
<!--            :edit-config="{trigger: 'click', mode: 'cell',showStatus: true, icon: 'fa fa-pencil'}"-->
<!--            :checkbox-config="{labelField: 'id'}"-->
<!--            height="400"-->
<!--            :data="bussMaterialPriceDetailTable.dataSource">-->
<!--              <vxe-table-column type="seq" width="60"></vxe-table-column>-->
<!--              <vxe-table-column field="materialCode" title="物料编号"></vxe-table-column>-->
<!--              <vxe-table-column field="materialName" title="物料名称"></vxe-table-column>-->
<!--              <vxe-table-column field="spec" title="规格"></vxe-table-column>-->
<!--              <vxe-table-column field="factory" title="生产厂家"></vxe-table-column>-->
<!--              <vxe-table-column field="taxPrice" title="含税" :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>-->
<!--              <vxe-table-column field="noTaxPrice" title="不含税" :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>-->
<!--            <vxe-table-column field="freight" title="运费不含税" :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>-->
<!--            <vxe-table-column field="price" title="本月价格（不含税）" :edit-render="{name: '$input', props: {type: 'number'}}" show-overflow></vxe-table-column>-->
<!--            <vxe-table-colgroup title="基本信息">-->
<!--              <vxe-table-column type="seq" width="60"></vxe-table-column>-->
<!--              <vxe-table-column field="name" title="Name"></vxe-table-column>-->
<!--            </vxe-table-colgroup>-->
<!--            <vxe-table-colgroup title="更多信息">-->
<!--              <vxe-table-column field="role" title="Role"></vxe-table-column>-->
<!--              <vxe-table-colgroup title="详细信息">-->
<!--                <vxe-table-column field="sex" title="Sex"></vxe-table-column>-->
<!--                <vxe-table-column field="age" title="Age"></vxe-table-column>-->
<!--              </vxe-table-colgroup>-->
<!--            </vxe-table-colgroup>-->
<!--            <vxe-table-colgroup title="分类信息">-->
<!--              <vxe-table-column field="date3" title="Date"></vxe-table-column>-->
<!--            </vxe-table-colgroup>-->
<!--            <vxe-table-column field="address" title="Address" show-overflow></vxe-table-column>-->


<!--            <vxe-table-column title="操作" width="200" show-overflow>-->
<!--              <template v-slot="{ row }">-->
                <!--                  <template v-if="$refs.xTable.isActiveByRow(row)">-->
                <!--                    <vxe-button type="text" @click="saveRowEvent(row)">保存</vxe-button>-->
                <!--                    <vxe-button type="text" @click="cancelRowEvent(row)">取消</vxe-button>-->
                <!--                  </template>-->
                <!--                  <template v-else>-->
                <!--                    <vxe-button type="text" icon="vxe-icon--edit-outline"  @click="editRowEvent(row)">编辑</vxe-button>-->
                <!--                  </template>-->

                <!--                  <vxe-button type="text" icon="fa fa-trash-o">删除</vxe-button>-->
<!--                <a-popconfirm-->
<!--                  title="确认删除?"-->
<!--                  @confirm="() => onDelete(row)"-->
<!--                >-->
<!--                  <vxe-button type="text" icon="fa fa-trash-o">删除</vxe-button>-->

<!--                </a-popconfirm>-->

<!--              </template>-->
<!--            </vxe-table-column>-->
<!--          </vxe-table>-->
          <a-row>
            <!-- 新增 -->
            <a-col :span="12">
              <a-space>
              <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="large"
                @click="addMadial">
                新增
              </a-button>
              </a-space>
            </a-col>
          </a-row>
          <a-table bordered
                   ref='table'
                   :data-source="bussMaterialPriceDetailTable.dataSource"
                   tableLayout='fixed'
                   :columns="bussMaterialPriceDetailTable.columns"
                   :rowKey="(record,index)=>{return index}"
                   :scroll="{ x: 1500,y: 500 }">
            <template slot="taxPrice" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'taxPrice', $event)" ></editable-cell>
            </template>
            <template slot="noTaxPrice" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'noTaxPrice', $event)" ></editable-cell>
            </template>
            <template slot="freight" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'freight', $event)" ></editable-cell>
            </template>
            <template slot="price" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'price', $event)" ></editable-cell>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-space>
<!--                <a @click="handleEdit(record)">编辑</a>-->
                <a-popconfirm
                  title="确认删除?"
                  @confirm="() => onDelete(record)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>

        </a-tab-pane>
      </a-tabs>

     <erp-goods-list-model ref="selectGoodsList"
                           category="4"
                           @goodsOk="goodsOk"
                           checkval='checkbox'>
     </erp-goods-list-model>

    </a-spin>


</template>

<script>
  import ErpGoodsListModel from "./ErpGoodsListModal";
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
  import EditableCell from '@comp/table/EditableCell'
  import { getAction, httpAction, postAction, putAction } from '@api/manage'

  export default {
    name: 'BussMaterialPriceForm',
    mixins: [JVxeTableModelMixin],
    components: {
      EditableCell,ErpGoodsListModel
    },
    data() {
      return {
        visible: false,
        ipagination: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          code:''
        },
        validatorRules: {
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['bussMaterialPriceDetail', ],
        tableKeys:['bussMaterialPriceDetail', ],
        activeKey: 'bussMaterialPriceDetail',
        // 原料价格执行表明细
        bussMaterialPriceDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '#',
              dataIndex: '',
              key: 'rowIndex',
              width: 60,
              align: "center",
              customRender: function (t, r, index) {
                return parseInt(index) + 1;
              }
            },
            // {
            //   title: '原料id',
            //   dataIndex: 'materialId',
            // },
            {
              title: '物料编号',
              dataIndex: 'materialCode',
            },
            {
              title: '物料名称',
              dataIndex: 'materialName',
            },
            {
              title: '规格',
              dataIndex: 'spec',
            },
            {
              title: '供应商/生产厂家',
              dataIndex: 'supplierName',
              ellipsis: true
            },
            {
              title: '出厂价格',
              children: [
                {
                  title: '含税价格',
                  dataIndex: 'taxPrice',
                  width: 150,
                  scopedSlots: { customRender: 'taxPrice' },
                },
                {
                  title: '不含税价格',
                  dataIndex: 'noTaxPrice',
                  width: 150,
                  scopedSlots: { customRender: 'noTaxPrice' },
                },
              ]
            },
            {
              title: '运费',
              dataIndex: 'freight',
              width: 150,
              scopedSlots: { customRender: 'freight' },
            },
            {
              title: '本月价格',
              dataIndex: 'price',
              width: 150,
              scopedSlots: { customRender: 'price' },
            },
            {
              title: '操作',
              dataIndex: 'operation',
              fixed: 'right',
              width: 150,
              scopedSlots: { customRender: 'operation' },
            },

          ]
        },
        url: {
          add: "/material/price/bussMaterialPrice/add",
          edit: "/material/price/bussMaterialPrice/edit",
          bussMaterialPriceDetail: {
            list: '/material/price/bussMaterialPrice/queryBussMaterialPriceDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      getSequenceNum() {
        let url = "/sys/fillRule/executeRuleByCode/yljgzxb";
        putAction(url, {}).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model.code = res.result;
          }
        })
      },
      onCellChange(record, dataIndex, value) {
        this.$set(record, dataIndex,value)
      },
      addMadial(){
        this.$nextTick(() => {
          this.$refs.selectGoodsList.add();
        })
      },
      goodsOk(data){
        if(data.length > 20){
          this.$message.warning('一次只能添加二十条')
          return;
        }
        let filteredJsonArray = data.map(user => {
          const { id: goodsId, supplierId } = user;
          return { goodsId, supplierId };
        });
        this.confirmLoading = true
        postAction('/base/erpGoods/list/goods/supplier',{list:filteredJsonArray})
          .then((res)=>{
            let _this = this;
            const { result } = res
            const { dataSource } = this.bussMaterialPriceDetailTable
            result.forEach((item)=>{
              let detail = {}
              detail.materialId = item.id
              detail.materialCode = item.code
              detail.materialName = item.name
              detail.spec = item.noneSpec
              detail.supplierId = item.supplierId
              detail.supplierName= item.supplierName
              detail.priceId = _this.model.id
              dataSource.push(detail)
            })
          }).finally(()=>{
            this.confirmLoading = false
        })
      },
      handleEdit(){

      },

      onDelete(record){
        const dataSource = [...this.bussMaterialPriceDetailTable.dataSource];
        this.bussMaterialPriceDetailTable.dataSource = dataSource.filter(item => item !== record);
        // if(this.model.details || this.model.details.length == 0){
        //   this.supplier = {};
        // }
      },
     addBefore(){
            this.bussMaterialPriceDetailTable.dataSource=[]
       this.getSequenceNum()
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussMaterialPriceDetail.list, params, this.bussMaterialPriceDetailTable)
        }
      },
      //校验所有一对一子表表单
    validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
    },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          bussMaterialPriceDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     close() {
        this.visible = false
        this.$emit('close')
        this.$refs.form.clearValidate();
      },
      submitForm() {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            this.$set(this.model,'bussMaterialPriceDetailList',this.bussMaterialPriceDetailTable.dataSource)
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>

<style scoped>
</style>